<template>
    <div class="upload" v-bind="$attrs">
        <svg-icon style="font-size:inherit;" v-if="!isUpload" name="add" @click="trigger" />
        <img class="avatar" @click="trigger" :src="imgSrc" alt="avatar" v-else>
        <input ref="files" accept=".jpg,.png,.jpeg,.gif" @change="getUploadFile($event)" type="file" v-show="false"
            :multiple="false">
    </div>
</template>
<script lang='ts' setup>
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue';

interface UploadProps {
    src?: string
}

const props = defineProps<UploadProps>()

const emit = defineEmits(["upload"])

let files = ref()
const trigger = () => {
    files.value.click()
}
let isUpload = ref(false)
let imgSrc = ref()
const getUploadFile = (evt: any) => {
    const file = evt.target.files[0] as File
    if (!file) return
    if (file.size > 1024 * 1024 * 5) return ElMessage.error("文件过大！")
    imgSrc.value = file
    let reader = new FileReader();
    reader.onload = function (evt: any) {
        imgSrc.value = evt.target.result;
    };
    reader.readAsDataURL(file);
    emit("upload", file)
    isUpload.value = true
}
const clearFile = () => {
    files.value.files = undefined
    isUpload.value = false
    imgSrc.value = ""
}
defineExpose({
    clearFile,
})

watch(() => props.src, (v) => {

    if (v) {
        isUpload.value = true
        imgSrc.value = import.meta.env.VITE_BASEURL + v
    }
}, {
    deep: true,
    immediate: true
})

</script>
<style lang="less" scoped>
.upload {
    width: 40px;
    height: 40px;
    border: 1px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.5s;
    border-radius: 100%;
    overflow: hidden;
    position: relative;
    &:hover {
        .el-icon {
            color: #999;
        }

        border: 1px solid #999;
    }

    .el-icon {
        cursor: pointer;
        color: #eee;
        transition: all 0.5s;
    }

    .avatar {
        width: 100%;
        height: 100%;
        cursor: pointer;
        transition: all 0.3s;
        position: relative;

        &:hover {
            transform: scale(1.1);
            
        }
    }
}
</style>